/*
 * @Date: 2022-08-01 14:47:52
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:启动核心服务
 * @LastEditTime: 2022-08-01 15:15:39
 * @FilePath: \server\system\init.go
 */
package system

import (
	"context"
	"embed"
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"runtime"
	"syscall"
	"time"

	"go2admin_pure/app"
	"go2admin_pure/system/core/config"
	"go2admin_pure/system/core/db"
	"go2admin_pure/system/core/log"
	"go2admin_pure/system/core/task"
	"go2admin_pure/system/core/trans"
	"go2admin_pure/system/core/ws"
	"go2admin_pure/system/router"
	"go2admin_pure/system/util/str"
	"go2admin_pure/system/util/sys"
)

func Init(staticFs embed.FS) {
	basedir := sys.ExecutePath() + "\\" //根目录
	//在线用户Id
	//GenApiDoc()  //生成api文档
	config.InitConfig(basedir + "config.toml")

	log.InitLog() //初始化日志

	db.InitConn()         //初始化系统数据库
	app.InitAppDb()       //初始化app的数据库表
	trans.InitTrans("en") //初始化翻译

	r := router.InitRouter(staticFs)
	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", config.Instance().App.HttpPort),
		Handler:        r,
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   30 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	fmt.Printf(`运行地址:http://127.0.0.1:%d`, config.Instance().App.HttpPort)
	go func() {
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Write(log.Error, err.Error())
			os.Exit(0)
		}
	}()
	go ws.Init()         //初始化websocket
	go task.Init()       //初始化system任务服务
	go app.InitAppTask() //初始化app任务服务

	shutDown(s)
}

func shutDown(s *http.Server) {
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	fmt.Println("Shutdown Server ...")

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	sqlDB, _ := db.Instance().DB()
	err := sqlDB.Close()
	if err != nil {
		log.Write(log.Fatal, "Close DB error:"+err.Error())
	}

	if err := s.Shutdown(ctx); err != nil {
		log.Write(log.Fatal, "Server Shutdown:"+err.Error())
	}
	fmt.Println("Server exiting")
}

//生成文档
//必须依赖 npm install apidoc -g
func GenApiDoc() {
	basedir := sys.ExecutePath()
	parentDir := str.BeforeLast(basedir, "\\") + "\\"
	//cmdline := "apidoc -c " + parentDir + "apidoc\\apidoc.json -i " + parentDir + "server\\system\\controller -o " + parentDir + "server\\apidoc -t " + parentDir + "apidoc\\template"
	cmdline := parentDir + "GenApidoc.bat"
	fmt.Println(runtime.GOOS)

	if runtime.GOOS == "windows" {
		// 执行命令，并返回结果

		cmd := exec.Command("cmd", "/c", "start "+cmdline)
		cmd.Dir = parentDir
		cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
		err := cmd.Run()
		if err != nil {
			panic(err)
		}

	}

}
